class UsersController < ApplicationController
  layout "main"
  before_filter :admin?, :only=>[:show]
  after_filter :post_log
  auto_complete_for :user, :sport

  def show
    require "format_string"
    @user = User.find params[:id]
  end
  def show_detail
    @user = User.find params[:id]
    @syllabuses = []
    registrations = Registration.find :all, :conditions => ["user_id=?",@user.id], :order => "id ASC"
    if(registrations.present?)
      registrations.each do |item|
        if(not @syllabuses.include?(item.syllabus_opening.syllabus))
          @syllabuses << item.syllabus_opening.syllabus
        end
      end
    end
    render :action=>"show_detail", :layout=>"main_no"
  end

  def company_profile
    @user = User.find params[:id]
    render :action=>"company_profile", :layout=>"main_no"
  end

  def remove_user
    search= params[:search]||""
    @users = User.paginate(:all, :page => params[:page], :conditions=>"login LIKE '%#{search}%'", :per_page => 25)
  end
  def destroy_user
    user = User.find params[:id]
    flash[:notice]= "ลบบัญชีผู้ใช้ #{user.login} เรียบร้อยแล้ว"
    user.destroy
    redirect_to :action => "remove_user"
  end
  def ban_chat
    user= User.find params[:id]
    user.update_attribute(:ban_chat, !user.ban_chat)
    redirect_to :controller => "report", :action => "chat", :page=>params[:page]
  end
  def login
    # login page
  end
  def change_password
    @u= User.find session[:user_id]
  end
  def forgot_password
  end
  def newpass( len )
    # chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
    chars = ("0".."9").to_a
    newpass = ""
    1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
    return newpass
  end
  def receive_password
    user = User.find_by_email(params[:email])
    msg = ""
    if user
      ## random password and encrypted ##
      new_password = newpass(4)
      pub_key =  Crypto::Key.from_file('turac_key.pub')
      user.epassword= pub_key.encrypt(new_password)
      user.password= Digest::SHA1.hexdigest(new_password)
      user.save!
      ###############
      mail_body = "ชื่อผู้ใช้งาน : "+user.login+"\nรหัสผ่่านใหม่ : "+new_password
      Mail.sendmail(DlearnUtility.get_system_email, user.email, "ท่านได้รับรหัสผ่านใหม่สำหรับระบบ E-learning", mail_body)
      msg = 'ระบบได้ส่งรหัสผ่านใหม่ให้ท่านเป็นที่เรียบร้อยแล้ว'
    else
      msg = 'ไม่พบอีเมล์ตามที่ท่านระบุ'
    end
    flash[:notice] = msg
    redirect_to_root
  end
  def reset_password
    @u= User.find session[:user_id]
    user= User.authenticate(@u.login, params[:password])
    if user && params[:new_password]==params[:confirm_new_password]
      pub_key =  Crypto::Key.from_file('turac_key.pub')
      user.epassword= pub_key.encrypt(params[:new_password])
      user.password= Digest::SHA1.hexdigest(params[:new_password])
      user.save!
      msg = 'ได้ทำการเปลี่ยนรหัสผ่านเป็นที่เรียบร้อยแล้ว'
      flash[:notice] = msg
      redirect_to_root
    else
      msg = '<font color=red>ไม่สามารถทำการเปลี่ยนรหัสผ่าน เนื่องจากท่านกรอกข้อมูลไม่ถูกต้อง</font>'
      flash[:notice] = msg
      render :action=>:change_password
    end
  end
  def reset_password2
    @u= User.find params[:user_id]
    pub_key =  Crypto::Key.from_file('turac_key.pub')
    user= @u
    user.epassword= pub_key.encrypt(@u.login)
    user.password= Digest::SHA1.hexdigest(@u.login)
    user.save!
    render :text=>"done"
  end
#  def test
#     @user = User.find_by_email("comnas@gmail.com")
#     @password = "12345"
#     @message = DlearnUtility.get_register_body
#     mail_body = render_to_string :action => "test", :template => "notifier/register_send", :layout => false
#     render :text => mail_body
#  end
  def create
    @user= User.new params[:user]
    @password = params[:user][:password]
    if @password != params[:user][:password_confirmation]
      flash[:notice]= "รหัสผ่านไม่ตรงกับรหัสยืนยัน"
      @user.password= ""
      @user.password_confirmation= ""
      render :action=>:signup
    else
      @user.ip= request.env["REMOTE_ADDR"]
      be_date= @user.dob
      ad_date= Date.new be_date.year-543, be_date.month, be_date.day
      @user.dob= ad_date
      @user.password= Digest::SHA1.hexdigest(@password)
#      process_pic
      if @user.save
        # TODO: Notifier.deliver_signup_thanks(@user, params[:user][:password]) if params[:app]=='dloc_el'
        @message = DlearnUtility.get_register_body
        mail_body = render_to_string :action => "create", :template => "notifier/register_send", :layout => false
        Mail.sendmail(DlearnUtility.get_system_email, @user['email'], DlearnUtility.get_register_subject, mail_body)
        msg = 'ท่านได้ลงทะเบียนเป็นที่เรียบร้อยแล้ว กรุณาล็อกอินเข้าสู่ระบบ'
        flash[:notice] = msg
        redirect_to_root
      else
        render :action=>:signup
#	redirect_to :action=>:signup, :layout=>session[:theme]
      end
    end
  end

  def fbcreate
    @user= User.new params[:user]
    @password = params[:user][:password]
    if @password != params[:user][:password_confirmation]
      flash[:notice]= "รหัสผ่านไม่ตรงกับรหัสยืนยัน"
      @user.password= ""
      @user.password_confirmation= ""
      render :action=>:signup
    else
      @user.ip= request.env["REMOTE_ADDR"]
      be_date= @user.dob
      ad_date= Date.new be_date.year-543, be_date.month, be_date.day
      @user.dob= ad_date
      @user.password= Digest::SHA1.hexdigest(@password)
#      process_pic
      if @user.save
        # TODO: Notifier.deliver_signup_thanks(@user, params[:user][:password]) if params[:app]=='dloc_el'
        session[:user] = @user
        session[:user_id] = @user.id
        redirect_to_root
      else
        render :action=>:checkfb, :id=>params[:id]
      end
    end
  end

  def c_create
    @user= User.new params[:user]
    @password = params[:user][:password]
    if @password != params[:user][:password_confirmation]
      flash[:notice]= "รหัสผ่านไม่ตรงกับรหัสยืนยัน"
      @user.password= ""
      @user.password_confirmation= ""
      render :action=>:c_signup
    else
      @user.ip= request.env["REMOTE_ADDR"]
      be_date= @user.dob
      ad_date= Date.new be_date.year-543, be_date.month, be_date.day
      @user.dob= ad_date
      @user.password= Digest::SHA1.hexdigest(@password)
      @user.role = 'C'
#      process_pic
      if @user.save
        # TODO: Notifier.deliver_signup_thanks(@user, params[:user][:password]) if params[:app]=='dloc_el'
        @message = DlearnUtility.get_register_body
        mail_body = render_to_string :action => "create", :template => "notifier/register_send", :layout => false
        Mail.sendmail(DlearnUtility.get_system_email, @user['email'], DlearnUtility.get_register_subject, mail_body)
        msg = 'ท่านได้ลงทะเบียนเป็นที่เรียบร้อยแล้ว กรุณาล็อกอินเข้าสู่ระบบ'
        flash[:notice] = msg
        redirect_to_root
      else
        render :action=>:c_signup
#	redirect_to :action=>:signup, :layout=>session[:theme]
      end
    end
  end

  def authenticate
    user = User.authenticate(params[:username], params[:password])
    if user
      session[:user_id]= user.id
#      session[:user]= user
    else
      flash[:notice]= "รหัสผ่านไม่ถูกต้อง กรุณาตรวจสอบอีกครั้ง"
    end
    redirect_to "/"
  end
  def logout
    chat_user_leave
    reset_session
    redirect_to "/"
  end
  def signup
    @user= User.new
  end

  def c_signup
    @user= User.new
  end

  def update_amphoe
    @amphoes= Amphoe.all :conditions=>"LEFT(code,2)='#{params[:id]}'", :order=>"code"
    render :layout=>false
  end
  def update_tambon
    @tambons= Tambon.all :conditions=>"LEFT(code,4)='#{params[:id]}'", :order=>"code"
    render :layout=>false
  end

  def process_login
    uid = params[:uid]
    user = User.find(:first, :conditions=>["facebook_id=?", uid])
    if user
      session[:user] = user
      session[:user_id]= user.id
      redirect_to :controller=>"main"
    else
      redirect_to :action=>"mapuser", :uid=>uid
    end
  end

  def mapuser
    @uid = params[:uid]
    render :action=>"mapuser"
  end

  def save_mapuser
    user = User.authenticate(params[:username], params[:password])
    if user
      old_user = User.find(:first, :conditions=>["facebook_id=?", params[:id]])
      if old_user
        old_user.facebook_id = nil
        old_user.save
      end
      user.facebook_id = params[:id]
      user.save
      session[:user]= user
      session[:user_id]= user.id
      redirect_to :controller=>"main"
    else
      render :text=>"Username หรือ รหัสผ่านผิดพลาด", :layout=>"main"
    end
  end

  def checkfb
    user = User.find(:first, :conditions=>["facebook_id=?", params[:id]])
    if user
      session[:user]= user
      session[:user_id]= user.id
    else
      @user = User.new
    end
    @uid = params[:id]
    render :action=>"checkfb"
  end

  private
  def process_pic
    photo= params[:user][:photo]
    unless photo.blank?
      id= create_upload(photo, params[:user][:login])
      @user.photo= url_for :controller=>"main", :action=>:pic, :id=>id
    end
    signature= params[:user][:signature]
    unless signature.blank?
      id= create_upload(signature, params[:user][:login])
      @user.signature= url_for :controller=>"main", :action=>:pic, :id=>id
    end
  end
  def create_upload(photo, login="")
    tcid_upload= TcidUpload.new :description=>'photo',
      :content=>photo.read, :created_by=>login,
      :filename=>photo.original_filename
    extension= File.extname(photo.original_filename).gsub( /^\./, '' ).downcase
    tcid_upload.picture= %w(gif jpg png).include? extension
    tcid_upload.save
    tcid_upload.id
  end

end
